package tech.aistar.rsmd;

import tech.aistar.util.JdbcUtil;

import java.sql.*;
import java.util.Scanner;

/**
 * 本类用来演示: mysql客户端
 *
 * @author: success
 * @date: 2022/8/12 2:20 下午
 */
public class Client {
    public static void main(String[] args) {
        start();
    }

    public static void start(){
        Scanner sc = new Scanner(System.in);
        StringBuilder sqlBuilder = new StringBuilder();
        System.out.print("mysql> ");
        while(true){
            String sql = sc.nextLine();
            sqlBuilder.append(sql+" ");
            //判断是否sql输入完毕
            if(sql.endsWith(";")){
                execute(sqlBuilder.deleteCharAt(sqlBuilder.length()-2).toString().trim());
                sqlBuilder.delete(0,sqlBuilder.length());
                System.out.print("mysql> ");
            }else{
                System.out.print("     > ");
            }
        }
    }

    private static void execute(String sql) {
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        try {
            conn = JdbcUtil.getConnection();
            st = conn.createStatement();

            boolean flag = st.execute(sql);
            if(flag){
                //DQL
                //rs
                rs = st.getResultSet();
                //获取结果集元数据
                ResultSetMetaData rsmd = rs.getMetaData();
                //获取列数
                int cols = rsmd.getColumnCount();

                //输出查询的标题
                for (int i = 1; i <=cols ; i++) {
                    System.out.printf("%-20s",rsmd.getColumnName(i));
                }
                System.out.println();

                //遍历结果集
                while(rs.next()){
                    for (int i = 1; i <=cols; i++) {
                        System.out.printf("%-20s",rs.getObject(i));
                    }
                    System.out.println();
                }

            }else{
                //DML,DDL
                //受影响的行数
                int rows = st.getUpdateCount();
                System.out.println("Query OK, "+rows+" row affected (0.00 sec)");
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtil.close(conn,st,rs);
        }
    }
}
